package com.shouhuobao.take.parcel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.iseastar.guojiang.BaseActivity;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.model.PostCompanyBackBean;
import com.shouhuobao.take.model.PostCompanyBean;
import com.shouhuobao.take.utils.ExpressCompanyDataUtils;
import com.shouhuobao.take.utils.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import droid.frame.ui.utils.Utils;

/**
 * 包裹签收 选择快递公司 <br>
 * Created by joker on 2017/5/27
 */
public class ParcelExpressCompanyActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout layoutIndex;// 存放选择字母的父布局
    private ListView mListView;// 快递公司列表
    private TextView tv_show;// 展示提示字母
    private EditText mSerachET;// 搜索编辑框
    private FrameLayout mFrameLayout;// 正常显示的整体布局
    private ListView mSerachLV;// 搜索时展示使用
    private ParcelExpressCompanyAdapter mAdapter;
    private String[] indexStr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", //
            "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private static HashMap<String, Integer> selector;// 存放含有索引字母的位置
    // 常用+所有的,并且经过排序/拼音处理
    private static ArrayList<PostCompanyBean> newCompanys = new ArrayList<PostCompanyBean>();
    // 常用快递公司
    private static ArrayList<PostCompanyBean> companyCommons = null;
    // 从服务器请求回来的原始数据
    private static ArrayList<PostCompanyBean> companyAlls = null;
    private int height;// 字体高度
    private boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 请求快递公司列表数据
        if (newCompanys.isEmpty() || companyCommons == null || companyAlls == null) {
            //            companyAlls = ExpressCompanyDataUtils.getAllExpressCompanyData();
            //            companyCommons = ExpressCompanyDataUtils.getCommonExpressCompanyData();
            new AsyncTask<PostCompanyBackBean, Void, PostCompanyBackBean>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    showLoadingDialog(null);
                }

                @Override
                protected PostCompanyBackBean doInBackground(PostCompanyBackBean... postCompanyBackBeans) {
                    PostCompanyBackBean backBean = ExpressCompanyDataUtils.getExpressCompanyData();
                    return backBean;
                }

                @Override
                protected void onPostExecute(PostCompanyBackBean result) {
                    cancelLoadingDialog();
                    if (result != null) {
                        companyAlls = result.all;
                        companyCommons = result.common;
                        setData();
                    }else {
                        showToast("数据有误");
                        finish();
                    }
                }
            }.execute();
        } else {
            // 不作处理
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.take_postcompany_select);
        super.findViewById();
        getAppTitle().setCommonTitle("选择快递公司");
        layoutIndex = (LinearLayout) this.findViewById(R.id.layout);
        layoutIndex.setBackgroundColor(Color.parseColor("#00ffffff"));
        mListView = (ListView) findViewById(R.id.listView);
        tv_show = (TextView) findViewById(R.id.showTv);
        mSerachET = (EditText) findViewById(R.id.serachET);
        mSerachLV = (ListView) findViewById(R.id.serachLV);
        mFrameLayout = (FrameLayout) findViewById(R.id.normalFL);
        findViewById(R.id.serachTV).setOnClickListener(this);
        tv_show.setVisibility(View.GONE);
        mAdapter = new ParcelExpressCompanyAdapter(newCompanys, getContext(), 0);
        mListView.setAdapter(mAdapter);
        mSerachET.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        if (isEmpty(mSerachET.getText().toString())) {
                            mFrameLayout.setVisibility(View.VISIBLE);
                            mSerachLV.setVisibility(View.GONE);
                            mSerachLV.setAdapter(null);
                        } else {
                            mFrameLayout.setVisibility(View.GONE);
                            mSerachLV.setVisibility(View.VISIBLE);
                            mSerachLV.setAdapter(null);
                            serachData(mSerachET.getText().toString());
                        }
                    }
                }
            };

            @Override
            public void afterTextChanged(Editable s) {
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 500);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PostCompanyBean bean = (PostCompanyBean) mListView.getAdapter().getItem(position);
                if (bean != null) {
                    Intent intent = new Intent();
                    intent.putExtra("item", bean);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

            }
        });
        //搜索出来的结果、点击以后跳转
        mSerachLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PostCompanyBean bean = (PostCompanyBean) mSerachLV.getAdapter().getItem(position);
                if (bean != null) {
                    Intent intent = new Intent();
                    intent.putExtra("item", bean);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    /**
     * 根据关键字模糊搜索
     *
     * @param content 搜索的内容
     */
    private void serachData(String content) {
        ArrayList<PostCompanyBean> serachList = new ArrayList<PostCompanyBean>();
        if (companyAlls.size() > 0) {
            for (PostCompanyBean bean : companyAlls) {
                if (bean.getName().contains(content)) {
                    serachList.add(bean);
                }
            }
        }
        mSerachLV.setAdapter(new ParcelExpressCompanyAdapter(serachList, getContext(), 0));
    }

    /**
     * 重新排序获得一个新的List集合
     *
     * @param allNames
     */
    private void sortList(String[] allNames) {
        for (int i = 0; i < allNames.length; i++) {
            if (allNames[i].length() != 1) {
                for (int j = 0; j < companyAlls.size(); j++) {
                    PostCompanyBean item = companyAlls.get(j);
                    if (allNames[i].equals(item.getPinyinName())) {
                        PostCompanyBean p = new PostCompanyBean(item.getName(), item.getPinyinName(), item.getCode(), item.getImage());
                        newCompanys.add(p);
                    }
                }
            } else {
                newCompanys.add(new PostCompanyBean(allNames[i]));
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // 在oncreate里面执行下面的代码没反应，因为oncreate里面得到的getHeight=0
        if (!flag) {
            height = layoutIndex.getMeasuredHeight() / indexStr.length;
            getIndexView();
            flag = true;
        }
    }

    /**
     * 获取排序后的新数据
     *
     * @param beans
     * @return
     */
    public String[] sortIndex(List<PostCompanyBean> beans) {
        TreeSet<String> set = new TreeSet<String>();
        // 获取初始化数据源中的首字母，添加到set中
        for (PostCompanyBean bean : beans) {
            set.add(StringUtils.getPinYinHeadChar(bean.getName()).substring(0, 1));
        }
        // 新数组的长度为原数据加上set的大小
        String[] names = new String[beans.size() + set.size()];
        int i = 0;
        for (String string : set) {
            names[i] = string;
            i++;
        }
        String[] pinYinNames = new String[beans.size()];
        for (int j = 0; j < beans.size(); j++) {
            beans.get(j).setPinyinName(StringUtils.getPingYin(beans.get(j).getName().toString()));
            pinYinNames[j] = StringUtils.getPingYin(beans.get(j).getName().toString());
        }
        // 将原数据拷贝到新数据中
        System.arraycopy(pinYinNames, 0, names, set.size(), pinYinNames.length);
        // 自动按照首字母排序
        Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
        return names;
    }

    /**
     * 绘制索引列表
     */
    public void getIndexView() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < indexStr.length; i++) {
            final TextView tv = new TextView(this);
            tv.setLayoutParams(params);
            tv.setText(indexStr[i]);
            tv.setPadding(Utils.dpToPx(16, getResources()), 0, Utils.dpToPx(16, getResources()), 0);
            layoutIndex.addView(tv);
            layoutIndex.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    float y = event.getY();
                    int index = (int) (y / height);
                    if (index > -1 && index < indexStr.length) {// 防止越界
                        String key = indexStr[index];
                        if (selector != null && selector.size() > 0) {
                            if (selector.containsKey(key)) {
                                int pos = selector.get(key);
                                if (mListView.getHeaderViewsCount() > 0) {// 防止ListView有标题栏
                                    mListView.setSelectionFromTop(pos + mListView.getHeaderViewsCount(), 0);
                                } else {
                                    mListView.setSelectionFromTop(pos, 0);// 滑动到第一项
                                }
                            }
                        }
                        tv_show.setVisibility(View.VISIBLE);
                        tv_show.setText(indexStr[index]);
                    }
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            // layoutIndex.setBackgroundColor(getResources().getColor(R.color.app_line_color));
                            break;

                        case MotionEvent.ACTION_MOVE:

                            break;
                        case MotionEvent.ACTION_UP:
                            // layoutIndex.setBackgroundColor(Color
                            // .parseColor("#00ffffff"));
                            tv_show.setVisibility(View.GONE);
                            break;
                    }
                    return true;
                }
            });
        }
    }

    /**
     * 设置数据
     */
    private void setData() {
        if (companyCommons != null && companyCommons.size() > 0) {
            companyCommons.add(0, new PostCompanyBean("常用快递"));
            newCompanys.addAll(0, companyCommons);
        }
        if (companyAlls != null && companyAlls.size() > 0) {
            String[] allNames = sortIndex(companyAlls);
            sortList(allNames);
            selector = new HashMap<String, Integer>();
            for (int j = 0; j < indexStr.length; j++) {// 循环字母表，找出newPersons中对应字母的位置
                for (int i = 0; i < newCompanys.size(); i++) {
                    if (newCompanys.get(i).getName().equals(indexStr[j])) {
                        selector.put(indexStr[j], i);
                    }
                }
            }
            for (PostCompanyBean bean : companyCommons) {
                bean.setPinyinName(StringUtils.getPingYin(bean.getName().toString()));
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 点击搜索按钮
            case R.id.serachTV:
                mFrameLayout.setVisibility(View.GONE);
                mSerachLV.setVisibility(View.VISIBLE);
                mSerachLV.setAdapter(null);
                serachData(mSerachET.getText().toString());
                break;
        }
    }

}
